package com.mopeso.location;

import android.Manifest;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;


import com.cash.lemoloan.statisticlib.StatisticApplication;
import com.cash.lemoloan.statisticlib.StatisticContant;
import com.mopeso.MyApplication;
import com.mopeso.R;
import com.mopeso.Utils.PermissionUtil;

import java.util.ArrayList;
import java.util.List;


public class LocationService extends Service {

    private List<ILocation> mLocations = new ArrayList<>();
    private Handler mCancleHandler;                                 //定时取消的handler
    private boolean isLoop = false;                                 //是否是循环刷新定位调用的service
    private static final long LOOP_LOCATION_TIME = 60*60 * 1000;  //循环定位时间间隔,默认一小时
    private long LOCATION_OVERTIME = 180 * 1000;                 //设置定位超时时间，默认为180秒
    private long mLocationOverTime;
    private LocationData mLocationDataTemp = null;
    private int mLocationFailCount = 0;
    private int mLocationSuccessCount = 0;
    private boolean mLocationSuccess = false;                   //是否定位成功
    private boolean mLocationFail = false;                   //是否定位失败
    private boolean isFastLocation = false;              //是否以最快速度返回定位信息

    @Override
    public void onCreate() {
        super.onCreate();


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        NotificationManager notificationManager = (NotificationManager) MyApplication.getApplication().getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel mChannel = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(StatisticContant.CHANNEL_ID_STRING_LOC, StatisticApplication.getInstance().getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(mChannel);
            Notification notification = new Notification.Builder(getApplicationContext(), StatisticContant.CHANNEL_ID_STRING_LOC).build();
            startForeground(1, notification);
        }
        if (PermissionUtil.checkPermissionsGranted(Manifest.permission.ACCESS_COARSE_LOCATION)) {
//        mTelNet = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            mLocations.add(new GoogleLocation(MyApplication.getApplication(),locationCallback));
//        if(BaseApplication.isDebug){
            mLocations.add(new SystemLocation(MyApplication.getApplication(), locationCallback));
//        }
            mCancleHandler = new Handler();
            //开始定位操作，遍历执行每个定位sdk
            for (ILocation location : mLocations) {
                location.startLocation();
            }
        }
        if(null != intent){
            isLoop = intent.getBooleanExtra("loop",false);              //获取是否是循环刷新位置
            isFastLocation = intent.getBooleanExtra("isFastLocation",false);        //获取是否是以最快时间获取定位位置的方式
            mLocationOverTime = intent.getLongExtra("overtime",LOCATION_OVERTIME);      //获取设置的超时时间
        }else{
        }
        if (mCancleHandler !=null)
            postToClose();
        setLoopLocation();
        return Service.START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }



    @Override
    public void onDestroy() {
        if (null  != mCancleHandler){
            mCancleHandler.removeCallbacksAndMessages(null);
            mCancleHandler = null;
        }
        for (ILocation location : mLocations) {
            location.closeLocation();
        }

        super.onDestroy();
    }

    private void postToClose(){

        if (mCancleHandler != null){
            mCancleHandler.removeCallbacksAndMessages(null);
        }
        //延迟30秒等待定位，没返回则关闭服务
        mCancleHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (null != mLocationDataTemp){
                    locationSuccess(mLocationDataTemp);
                }else {

                    locationFail();
                }
            }
        }, mLocationOverTime);
    }



    private ILocationCallback locationCallback = new ILocationCallback() {
        @Override
        public synchronized void onLocationSuccess(LocationData locationData) {
            //定位成功但是数据为0的情况
            if (0 == Double.valueOf(locationData.latitude) || 0 == Double.valueOf(locationData.longitude)){

                //以防出现错误，定位成功但是经纬度为0
                mLocationFailCount ++;
                if (mLocationFailCount == mLocations.size()){
                    //如果所有定位方式全部定位失败

                    locationFail();
                }
                return;
            }
            mLocationSuccessCount ++ ;
            //定位成功的情况google优先原则
            if (isFastLocation || "google".equals(locationData.way)){
                locationSuccess(locationData);
            }else {
                if ((mLocationSuccessCount + mLocationFailCount) == mLocations.size()){
                    locationSuccess(locationData);
                }else {
                    mLocationDataTemp = locationData;
                }
            }
        }



        @Override
        public synchronized void onLocationFailed(LocationErrorType locationErrorType,String way,String message) {
            mLocationFailCount ++;
            if (mLocationFailCount + mLocationSuccessCount == mLocations.size()){
                if (null != mLocationDataTemp){
                    locationSuccess(mLocationDataTemp);
                }else {
                    //如果所有定位方式全部定位失败

                    locationFail();
                }
            }
        }
    };

    private void locationFail(){
        if (!mLocationFail){
            mLocationFail = true;
            if (!isLoop){
            }
            stopSelf();
        }
    }

    private void locationSuccess(LocationData locationData){

        if (!mLocationSuccess){
            mLocationSuccess = true;
            saveData(locationData);
            if (!isLoop){
            }
            //定位成功直接结束服务
        }
        stopSelf();
    }

    private void saveData(final LocationData locationData){
        StatisticContant.latitude = locationData.latitude;
        StatisticContant.longitude = locationData.longitude;
/*         List<Address> addresses; Geocoder geocoder = new Geocoder(UIUtils.getContext(), Locale.getDefault());
        String addStr = null;
       try {
            addresses = geocoder.getFromLocation(Double.valueOf(latitude),Double.valueOf(longitude), 1);
            String address = addresses.get(0).getAddressLine(0);
            String city = addresses.get(0).getLocality();
            String state = addresses.get(0).getAdminArea();
            String zipCode = addresses.get(0).getPostalCode();
            String country = addresses.get(0).getCountryCode();
            addStr = address + "," + city + "," + state + "," + zipCode + "," + country;
            LogUtil.e("addStr " + addStr);
        }
            catch (IOException e) {
            e.printStackTrace();
        }*/

        if (isLoop){
//            StatManager.init(this, new Stat.OnUploadResponseListener() {
//                @Override
//                public void onResult(String s, Stat.Result result) {
//                    StatManager.uploadLoc01(locationData.latitude,locationData.longitude,extras);
//                }
//            });
        }else {
//            StatManager.uploadLoc01(locationData.latitude,locationData.longitude,extras);
        }
    }

    private void setLoopLocation(){
        try{
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            Intent alarmIntent = new Intent(this, LocationService.class);
            alarmIntent.putExtra("loop", true);
            PendingIntent pendingIntent = PendingIntent.getService(this, 100, alarmIntent, 0);
            if (pendingIntent != null){
                alarmManager.cancel(pendingIntent);
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + LOOP_LOCATION_TIME, pendingIntent);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()  + LOOP_LOCATION_TIME, pendingIntent);
            } else {
                alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+ LOOP_LOCATION_TIME, pendingIntent);
            }
        }catch (Exception e){

        }
    }
}
